package de.jadehs.cosima.ui;

import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleConstants;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.IConsoleView;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.xtext.parser.IParseResult;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.ui.editor.XtextEditor;
import org.eclipse.xtext.util.concurrent.IUnitOfWork;

import de.jadehs.cosima.Cosima;

public class CosimaUIUtil {
	private static final String COSIMA = "COSIMA";

	public static MessageConsole getCosimaConsole(IWorkbenchPage page) {
		MessageConsole console = null;
		{
			ConsolePlugin plugin = ConsolePlugin.getDefault();
			IConsoleManager conMan = plugin.getConsoleManager();
			IConsole[] existing = conMan.getConsoles();

			for (int i = 0; i < existing.length; i++) {
				if (COSIMA.equals(existing[i].getName())) {
					console = (MessageConsole) existing[i];
				}
			}

			if (console == null) {
				console = new MessageConsole(COSIMA, null);
				conMan.addConsoles(new IConsole[] { console });
			}
		}

		if (console != null && page != null) {
			try {
				IConsoleView view = (IConsoleView) page
						.showView(IConsoleConstants.ID_CONSOLE_VIEW);
				view.display(console);
			} catch (PartInitException e) {
				;
			}
		}

		return console;
	}

	public static Cosima getCosimaModel(IWorkbench wb) {
		IEditorPart editor = wb.getActiveWorkbenchWindow().getActivePage()
				.getActiveEditor();
		if (editor instanceof XtextEditor) {
			XtextEditor xed = (XtextEditor) editor;

			final Cosima[] cosima = new Cosima[1];
			xed.getDocument().readOnly(new IUnitOfWork.Void<XtextResource>() {
				public void process(XtextResource resource) throws Exception {
					IParseResult parseResult = resource.getParseResult();
					cosima[0] = (Cosima) parseResult.getRootASTElement();
				}
			});

			return cosima[0];
		}

		return null;
	}
}
